<template>
  <div class="wrap">
    <div class="search-wrap">
      <el-input
        v-model.trim="search.departmentname"
        @keyup.enter="getDepartmentList"
        placeholder="模糊搜索部门名"
        style="width: 350px"
      />
      <el-button
        class="search-class"
        type="primary"
        @click.stop="getDepartmentList"
        >查询</el-button
      >
    </div>
    <div class="table-header">
      <div>部门管理</div>
      <el-button class="add" type="primary" @click="addRow">新增</el-button>
    </div>
    <el-table :data="roleList" style="width: 100%">
      <!-- <el-table-column prop="id" label="id"> </el-table-column> -->
      <el-table-column prop="departmentname" label="部门名称" width="150">
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间"> </el-table-column>
      <el-table-column prop="updated_at" label="更新时间"> </el-table-column>
      <el-table-column label="拥有角色" width="200">
        <template v-slot="scope">
          {{ scope.row.roles.map((role) => role.rolename).join("、") }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template v-slot="scope">
          <el-button
            @click.stop="departmentAddRole(scope.row)"
            type="primary"
            size="small"
          >
            分配角色
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click.stop="editorRow(scope.row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            title="确认要删除该列?"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="deleteRow(scope.row)"
          >
            <template #reference>
              <el-button> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-footer">
      <el-pagination
        background
        @current-change="currentChange"
        :page-size="pagination.pageSize"
        layout="prev, pager, next"
        :total="pagination.total"
      />
    </div>

    <el-dialog
      v-model="dialogDepartmentVisible"
      :close-on-click-modal="false"
      :title="dialogDepartmentTripType == 1 ? '新增' : '编辑'"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="部门名称" label-width="140px">
          <el-input v-model.trim="form.departmentname"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogDepartmentVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      v-model="dialogRoleVisible"
      :close-on-click-modal="false"
      title="授权"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="角色（多选）" label-width="140px">
          <el-checkbox-group v-model="form.roles">
            <el-checkbox
              :label="role.id"
              v-for="(role, index) in allRoleList"
              :key="index"
              >{{ role.rolename }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "JddChromePluginsroleList",

  data() {
    return {
      dialogRoleVisible: false,
      dialogDepartmentVisible: false,
      dialogDepartmentTripType: 1, //1 新增 0 编辑
      search: {
        departmentname: "",
      },
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      form: {
        id: "",
        departmentname: "",
        roles: [],
      },
      roleList: [],
      allRoleList: [],
    };
  },

  async mounted() {
    await this.getDepartmentList();
    await this.getAllRoleList();
  },
  watch: {
    dialogDepartmentVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.form, {
            id: "",
            departmentname: "",
          });
        }
      },
    },
  },
  methods: {
    async getDepartmentList() {
      let ret = await request.get("/department/list", {
        departmentname: this.search.departmentname,
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      });
      if (ret.code == 200) {
        this.roleList = ret.data[0] || [];
        this.pagination.total = ret.data[1];
      }
    },
    async getAllRoleList() {
      let ret = await request.get("/role/list", {});
      if (ret.code == 200) {
        this.allRoleList = ret.data[0] || [];
      }
    },
    async findDepartmentSelfRoles(departmentId) {
      let ret = await request.get(`/department/hasroles/${departmentId}`);
      if (ret.code == 200) {
        this.form.roles = ret.data.map((item) => item.id) || [];
      }
    },
    async departmentAddRole(row) {
      this.form.id = row.id;
      this.findDepartmentSelfRoles(row.id);
      this.dialogRoleVisible = true;
    },
    async confirmAddRole() {
      let ret = {};
      if (this.dialogDepartmentTripType == 1) {
        ret = await request.post("/department/add", {
          departmentname: this.form.departmentname,
        });
      } else {
        ret = await request.patch(`/department/${this.form.id}`, {
          departmentname: this.form.departmentname,
        });
      }

      if (ret.code == 200) {
        this.$message({
          message: this.dialogDepartmentTripType == 1 ? "新增成功" : "编辑成功",
          type: "success",
        });
        this.getDepartmentList();
        this.dialogDepartmentVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    addRow() {
      this.dialogDepartmentTripType = 1;
      this.dialogDepartmentVisible = true;
    },
    editorRow(row) {
      this.dialogDepartmentTripType = 0;
      this.dialogDepartmentVisible = true;
      this.form.id = row.id;
      this.form.departmentname = row.departmentname;
    },
    async deleteRow(row) {
      let ret = await request.delete(`/department/${row.id}`, {});
      if (ret.code == 200) {
        ElMessage.success("删除成功");
        this.getDepartmentList();
      }
    },
    async currentChange(pageSize) {
      this.pagination.currentPage = pageSize;
      this.getDepartmentList();
    },
    async confirmRole() {
      let ret = await request.post("/department/add/role", {
        departmentId: this.form.id,
        roleIds: this.form.roles,
      });
      if (ret.code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getDepartmentList();
        this.dialogRoleVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrap {
  .headPictureCol {
    width: 32px;
    height: 32px;
    overflow: hidden;
    border-radius: 50%;
  }
  .search-wrap {
    display: flex;
    margin-bottom: 15px;
    .search-class {
      margin-left: 20px;
    }
  }
  .table-header {
    display: flex;
    line-height: 50px;
    padding: 0 10px;
    justify-content: space-between;
    align-items: center;
  }
  .pagination-footer {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
